﻿Imports System.Windows.Threading

Public Class BalloonManager
    Private Shared WithEvents BalloonTimer As New DispatcherTimer
    Private Shared BalloonPlograms As New Queue(Of LiveProgram)
    Private Shared WithEvents NotifyIcon As Forms.NotifyIcon
    Private Shared LockObject As New Object

    Private Sub New()
    End Sub

    Public Shared Sub SetNotifyIcon(ByVal notifyIcon As Forms.NotifyIcon)
        BalloonManager.NotifyIcon = notifyIcon
    End Sub

    Public Shared Sub ShowBalloon(ByVal program As LiveProgram)

        SyncLock LockObject ' TODO 挙動がおかしい？　たぶん同じスレッドだからSyncいらん
            If BalloonPlograms.Count = 0 Then
                BalloonTimer.Interval = New TimeSpan(1)
            End If
            BalloonPlograms.Enqueue(program)
        End SyncLock
        BalloonTimer.Start()

    End Sub

    Private Shared Sub ShowBalloon(ByVal sender As Object, ByVal e As EventArgs) Handles BalloonTimer.Tick
        BalloonTimer.Stop()

        Dim program = BalloonPlograms.Dequeue

        Dim limit = program.StartDateTime.AddMinutes(My.Settings.AirMinutes).Subtract(Now).Minutes
        Dim footer As String
        If limit < 0 Then
            Do While limit < 0
                limit += My.Settings.AirMinutes
            Loop
            If limit > 28 Then
                footer = "(延長？ 残り" & limit.ToString & "分)"
            Else
                footer = "(延長 残り" & limit.ToString & "分)"
            End If
        Else
            footer = "(残り" & program.StartDateTime.AddMinutes(My.Settings.AirMinutes).Subtract(Now).Minutes.ToString & "分)"
        End If

        If NotifyIcon IsNot Nothing Then
            NotifyIcon.BalloonTipTitle = program.Title
            NotifyIcon.BalloonTipText = program.Content & vbCrLf & _
                                        program.Station.Name & " " & _
                                        program.StartDateTime.ToString("HH:mm") & _
                                        footer

            NotifyIcon.Tag = program.Uri
            NotifyIcon.ShowBalloonTip(5000) ' TODO Magic Num
        End If

        If BalloonPlograms.Count > 0 Then
            BalloonTimer.Interval = New TimeSpan(0, 0, 5)
            BalloonTimer.Start()
        End If
    End Sub

    Private Shared Sub NotifyIcon_BalloonTipClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon.BalloonTipClicked
        Try
            BrowserManager.OpenUri(DirectCast(NotifyIcon.Tag, Uri))
        Catch ex As Exception
        End Try
    End Sub

End Class
